define(["dojo/_base/declare",
        "widgets/baseWidget/BaseWidget",
        "dojo/_base/lang", "dojo/on",
        "dojo/query","dojo/topic",
        "widgets/mapWidget/MapWidget",
        "esri/layers/ArcGISDynamicMapServiceLayer",
        "esri/renderers/SimpleRenderer",
        "esri/layers/FeatureLayer",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/layers/LayerInfo",
        "esri/Color",
        "dojo/dom",
        "dojo/text!./templates/Template.html","esri/config"
   ],
    function(declare,BaseWidget, lang, on, query, topic,MapWidget,ArcGISDynamicMapServiceLayer,
            SimpleRenderer,FeatureLayer,SimpleLineSymbol,SimpleFillSymbol,LayerInfo,Color,dom,
             template,esriConfig) {
        return declare([BaseWidget], {
        	//模板页面
            templateString : template,
            treeObjJson:null,
            treeObjLayerND:null,
            Fealyer: null,
            constructor : function() {
            	this.inherited(arguments);
                this.treeObjJson = [];  // tree的构造json
                this.treeObjLayerND = [];
                this.FeaLyer = [];
            },
            //组件初始化方法
            postCreate : function() {
            	this.inherited(arguments);
            },

            startup:function(){
                this.inherited(arguments);
            },

            destroy:function(){
            	this.inherited(arguments);
            },
            // 初始化方法 url 传入mapservice的rest
            initTree:function(url){
            	esriConfig.defaults.io.proxyUrl = "proxy.jsp";
                var ADynamicMapServiceLay = new ArcGISDynamicMapServiceLayer(url);
                var map = dijit.byId("mapW").map;
                var thisObj = this;
                var addDiyDom = this.addDiyDom;
                var zTreeOnCheck = this.zTreeOnCheck;
                var zNodesOnClick = this.zNodesOnClick;
                var returnParentObj = this.returnParentObj;
                var treeObjJson = this.treeObjJson;
                var createTree = this.createTree;
                var treeObjLayerND = this.treeObjLayerND;
                Global.that = this;
                on(ADynamicMapServiceLay,"load",function(){
                    // 配置文件
                    var setting = {
                        check:{
                            enable:true,
                            chkboxType:{ "Y":"s","N":"s"},
                            chkStyle:"checkbox"
                        },
                        view:{
                            addDiyDom: addDiyDom
                        },
                        callback:{
                            onCheck: zTreeOnCheck,
                            onClick: zNodesOnClick
                        }
                    };
                    var ADynMapSvsLayerInfo = ADynamicMapServiceLay.layerInfos;
                    var ADyn = returnParentObj(ADynMapSvsLayerInfo);
                    for (var rp = 0; rp < ADyn.length; rp++) {
                        createTree(ADynMapSvsLayerInfo,ADyn[rp],null,thisObj);
                    }
                    zNodes = treeObjJson;  // 构造tree的json
                    Global.zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);   // 构建ztree
                    for (var ouer = 0; ouer < treeObjLayerND.length; ouer++) {
                        for (var iner = ouer; iner < treeObjLayerND.length; iner++) {
                            if (treeObjLayerND[ouer].id > treeObjLayerND[iner].id) {
                                var temp = treeObjLayerND[ouer];
                                treeObjLayerND[ouer] = treeObjLayerND[iner];
                                treeObjLayerND[iner] = temp;
                            }
                        }
                    }
                    var sxFeaLyer = [];
                    for (var fLrId = treeObjLayerND.length-1 ; fLrId >= 0; fLrId--) {  // 要素加载顺序很重要  这个严格按照用户url所配的样子来加载
                        var FeaLyer1 = new FeatureLayer(url + "/" + treeObjLayerND[fLrId].id);
                        sxFeaLyer.push(FeaLyer1);
                        map.addLayer(FeaLyer1);
                    }
                    for (var gfl = sxFeaLyer.length - 1 ; gfl >= 0; gfl--) {
                        thisObj.FeaLyer.push(sxFeaLyer[gfl]);
                    }
                    for(var gf = 0; gf < thisObj.FeaLyer.length; gf++){
                        on(thisObj.FeaLyer[gf],"load",function(){
                             this.setVisibility(false);
                        });
                    }
                });
            },
            // 循环执行  节点遍历是从叶子节点开始逐层向上
            addDiyDom:function(treeId, treeNode) {
                // 让父节点不添加slider
                if(treeNode.children.length){
                    return ;
                }else{
                    var liObj = $("#" + treeNode.tId);
                }
                var sliderStr = "<div class='ss' id='ss_"+ treeNode.tId +"'"+ "style='width: 100px; height: 30px;'></div> ";
                liObj.append(sliderStr);
                var mySlider = $(".ss").slider({
                    tooltip: "always",
                    step: 0.1,
                    formatter:function(value){
                        return value*10 +"%"
                    },
                    precision: 0.1,
                    value: 10
                });
                var Oslider = $('#ss_'+ treeNode.tId);
                var OsliderNext = Oslider.prev(".slider");
                OsliderNext.css("display","none");
            },
            // 选中的时候调用  ZTreeOnCheck 作为一个回调函数，本身属于tree对象，所以这里面的this不是指向widget
            zTreeOnCheck: function(event, treeId, treeNode) {
                // 选出子节点<实际节点的>
                var treeObj = Global.zTreeObj.getNodes();
                var arrTreeObj = Global.zTreeObj.transformToArray(treeObj);
                var arrChildNodes = [];
                for (var ato = 0; ato < arrTreeObj.length; ato++) {
                    if(arrTreeObj[ato].children.length == 0){
                        arrChildNodes.push(arrTreeObj[ato]);
                    }
                }
                // 选出当前选中的节点
               var seledNodes = [];
                for (var tob = 0; tob < arrChildNodes.length; tob++) {
                    if (arrChildNodes[tob].checked) {
                        seledNodes.push(arrChildNodes[tob]);
                    }
                }
                var currentFealyer = []; //存放当前符合选中的图层
                for(var fed = 0; fed < Global.that.FeaLyer.length; fed++ ){
                    for (var ckf = 0; ckf < seledNodes.length; ckf++) {
                        var GresultTreeId = seledNodes[ckf].tId.split("_")[1];
                        if(GresultTreeId - 1 == Global.that.FeaLyer[fed].layerId){
                            currentFealyer.push(Global.that.FeaLyer[fed]);
                        }
                    }
                }
                for(var gtr = 0; gtr < arrChildNodes.length; gtr++){
                    (function(gtr){
                        var Osl = $('#ss_' + arrChildNodes[gtr].tId);

                        Osl.on("slideStop",function(){
                            Global.that.FeaLyer[gtr].setOpacity(Osl.slider("getValue")/10);
                        });

                    })(gtr);
                }
                for (var curFf = 0; curFf < Global.that.FeaLyer.length; curFf++) {
                    Global.that.FeaLyer[curFf].setVisibility(false);
                }
                for (var curF = 0; curF < currentFealyer.length; curF++) {
                    currentFealyer[curF].setVisibility(true);
                }
            },

            zNodesOnClick:function(event,treeId,treeNode,clickFlag){
                var Oslider = $('#ss_'+ treeNode.tId);
                var OsliderNext = Oslider.prev(".slider");
                if(OsliderNext.css("display") == "block"){
                    OsliderNext.css("display", "none");
                }
                else if(OsliderNext.css("display") == "none"){
                    OsliderNext.css("display", "block");
                }
            },
              // 从传入的图层树中取出所有的父节点
            returnParentObj: function(ADynMapInfo){
                var resultParentObj = [];
                for (var ad = 0; ad < ADynMapInfo.length; ad++) {
                if(!(ADynMapInfo[ad].parentLayerId+1)){
                    resultParentObj.push(ADynMapInfo[ad]);
                   }
                }
                return resultParentObj;
            },
            // treeObj是构造json的对象   parentObj是父节点  obj是子节点  单个节点对象{}的构建
            createJson: function (treeobj){
                var treeObj = {};
                treeObj.name = treeobj.name;
                treeObj.children = [];
                treeObj.id = treeobj.id;
                return treeObj;
            },
            //  ADynMapSvsLayerInfo 存放图层节点数组   obj 当前处理节点对象   parentND 当前节点父节点 ，thisobj为wigit的this对象
            createTree: function(ADynMapSvsLayerInfo, obj, parentND,thisObj ){  // 处理的都是一个对象 ,传入for循环出来的对象
                var parentObj;
                if (!(obj.parentLayerId + 1)) {
                    parentObj = thisObj.treeObjJson;
                }else{
                    parentObj = parentND;
                }
                if (!obj.subLayerIds) {
                    var objJson1 = thisObj.createJson(obj);
                    if(!(obj.parentLayerId+1)){
                        thisObj.treeObjLayerND.push(objJson1);
                        parentObj.push(objJson1);
                    }else{
                        thisObj.treeObjLayerND.push(objJson1);
                        parentObj.children.push(objJson1);
                    }
                }else{
                    if (obj.parentLayerId) {
                        var objJson2 = thisObj.createJson(obj);
                        thisObj.treeObjJson.push(objJson2);
                        for (var k = 0; k < obj.subLayerIds.length; k++) {
                            thisObj.createTree(ADynMapSvsLayerInfo,ADynMapSvsLayerInfo[obj.subLayerIds[k]],objJson2,thisObj);
                        }
                    }else{
                        var objJson3 = thisObj.createJson(obj);
                        parentObj.children.push(objJson3);
                        var j = obj.subLayerIds.length;
                        while(j>0){
                            j--;
                            thisObj.createTree(ADynMapSvsLayerInfo,ADynMapSvsLayerInfo[obj.subLayerIds[j]],objJson3,thisObj);
                        }
                    }

                }
            }
    });
});
